<script setup>
import { ref, nextTick } from 'vue'
import ChannelSelect from "@/views/article/components/ChannelSelect.vue";
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import {artEditService, artGetDetailService, artPublishService} from "@/api/article.js";
import { baseURL } from '@/utils/request.js'
import axios from 'axios'
const drawer = ref(false)
const imgUrl = ref('')
const editorRef = ref(null)
const defaultForm = {
  title: '',
  cate_id: '',
  cover_img: '',
  content: '',
  state: ''
}
const formModel = ref({ ...defaultForm })
const handleClose = () => {
  drawer.value = false

}
const open = async (row) => {
  drawer.value = true
  if (row.cate_id) {
    // 编辑, 调用接口
    // formModel.value = {...row }
    // const res = await artGetDetailService({id: row.cate_id })
    // formModel.value = res.data.data
    // imgUrl.value = baseURL + formModel.value.cover_img
    // formModel.value.cover_img = await imageUrlToFile(imgUrl.value, formModel.value.cover_img)
    formModel.value = {
      title: row.title,
      cate_id: row.cate_id,
      cover_img: '',
      content: '',
      state: row.state
    }
    // console.log(res, '编辑详情')
  } else {
    // 添加
    formModel.value = {...defaultForm }
    imgUrl.value = ''
    nextTick(()=>{
      editorRef.value.setHTML('')
    })
  }
}
// 提交给后台, 需要是file 格式的, 将网络图片, 转成file格式
// 网络图片转成file对象, 需要转换一下
// 将网络图片地址转换为File对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' });
    const imageData = response.data;
    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], { type: response.headers['content-type'] });
    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type });
    return file;
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error);
    throw error;
  }
}

defineExpose({
  open
})

const onUploadFile = (uploadFile) => {
  // 预览图片
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  formModel.value.cover_img = uploadFile.raw
}

/*
* 发布文章
* */
const emit = defineEmits(['success'])
const onPublish = async (state) => {
  // console.log(state)
  // 将已发布还是草稿状态,存入 formModel
  formModel.value.state = state
  // 注意: 当前接口, 需要的是formData 对象
  // 将普通对象 = > 转换成 => formData对象
  const fd =  new FormData()
  for (const key in formModel.value) {
    fd.append(key, formModel.value[key])
  }
  // 发请求
  if (formModel.value.cate_id) {
    // await artEditService(fd)
    ElMessage.success('修改成功')
    drawer.value = false
    emit('success', 'edit')
  } else {
    // 添加操作
    // const res = await artPublishService(fd)
    // console.log(res, '添加发布')
    // 提示
    ElMessage.success('添加成功')
    drawer.value = false
    emit('success', 'add')
  }
}
</script>

<template>
  <el-drawer
    v-model="drawer"
    :title="formModel.cate_id ? '编辑文章' : '发布文章'"
    :direction="'rtl'"
    :before-close="handleClose"
    size="50%"
  >
    <!-- 发表文章表单 -->
    <el-form :model="formModel" ref="formRef" label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <channel-select v-model="formModel.cate_id"  width="100%" ></channel-select>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <el-upload
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <quill-editor ref="editorRef" theme="snow" v-model:content="formModel.content" contentType="html"></quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="onPublish('已发布')" type="primary">发布</el-button>
        <el-button @click="onPublish('草稿')" type="info">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped lang="scss">
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
